package com.example.showdemo;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private EditText edit;
    private TextView titleText;
    private TextView msgText;
    private Button clearText;

    private Handler handler = new Handler();//进行延时操作

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        titleText = (TextView)findViewById(R.id.titleText);
        edit = (EditText)findViewById(R.id.edit);
        msgText = (TextView)findViewById(R.id.msgText);
        clearText = (Button)findViewById(R.id.clearText);

        titleText.setText("NORMAL");
        edit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }
            @Override
            public void afterTextChanged(Editable s) {
                handleData(s.toString());
            }
        });

        clearText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                edit.setText("");
            }
        });
    }

    // 数据的处理，真实情况下可能是网络请求，磁盘存取，大量计算逻辑等等
    private  void handleData(String data) {
        if (TextUtils.isEmpty(data)) {
            msgText .setText("default msg");
            return;
        }
        msgText .setText("handle data ...");

        handler.removeCallbacksAndMessages(null);
        // 延迟来模拟网络或者磁盘操作
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                msgText .setText("handled data: $data");
            }
        },3000);
    }
}


